package kd;

import java.util.Stack;
import java.util.StringTokenizer;
public class MyDC {
    /**
     * constant for addition symbol
     */
    private final char ADD = '+';
    /**
     * constant for subtraction symbol
     */
    private final char SUBTRACT = '-';
    /**
     * constant for multiplication symbol
     */
    private final char MULTIPLY = '*';
    /**
     * constant for division symbol
     */
    private final char DIVIDE = '/';
    /**
     * the stack
     */
    private Stack<java.lang.Integer> stack;

    public MyDC() {
        stack = new Stack<>();
    }
    public int evaluate(String expr) {//计算输入的expr这个式子
        int  op1, op2, result=0;
        String token;
        //Integer operator;
        StringTokenizer tokenizer = new StringTokenizer(expr);
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();
            if(isOperator(token)){//遇到一个操作符就弹出两个操作数
                op2=stack.pop().intValue();
                op1=stack.pop().intValue();
                //System.out.println();
                result=evalSingleOp(token.charAt(0),op1,op2);
                stack.push(result);
            } else {
                stack.push(java.lang.Integer.valueOf(token));
            }
        }
        return result;
    }

    private boolean isOperator(String token) {
        return (token.equals("+") || token.equals("-") ||
                token.equals("*") || token.equals("/"));
    }

    private int evalSingleOp(char operation, int op1, int op2) {
        int result = 0;
        switch (operation) {
            case ADD:
                result = op1 + op2;
                break;
            case SUBTRACT:
                result = op1 - op2;
                break;
            case MULTIPLY:
                result = op1 * op2;
                break;
            case DIVIDE:
                result = op1 / op2;
        }
        return result;
    }
}